#include "models.h"
#include <QUuid>
#include <QJsonDocument>
#include <QDebug>

namespace RestaurantSystem {

// ============================================================================
// Customer 实现
// ============================================================================

Customer::Customer(const QString& username, const QString& passwordHash, const QString& email) 
    : id(QUuid::createUuid().toString(QUuid::WithoutBraces))
    , username(username)
    , passwordHash(passwordHash)
    , email(email)
    , registrationDate(QDateTime::currentDateTime())
    , lastLoginDate(QDateTime::currentDateTime())
{
}

QJsonObject Customer::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["username"] = username;
    json["passwordHash"] = passwordHash;
    json["plainPassword"] = plainPassword;
    json["email"] = email;
    json["registrationDate"] = registrationDate.toString(Qt::ISODate);
    json["lastLoginDate"] = lastLoginDate.toString(Qt::ISODate);
    return json;
}

Customer Customer::fromJson(const QJsonObject& json) {
    Customer customer;
    customer.id = json["id"].toString();
    customer.username = json["username"].toString();
    customer.passwordHash = json["passwordHash"].toString();
    customer.plainPassword = json["plainPassword"].toString();
    customer.email = json["email"].toString();
    customer.registrationDate = QDateTime::fromString(json["registrationDate"].toString(), Qt::ISODate);
    customer.lastLoginDate = QDateTime::fromString(json["lastLoginDate"].toString(), Qt::ISODate);
    return customer;
}

bool Customer::isValid() const {
    return !id.isEmpty() && !username.isEmpty() && !passwordHash.isEmpty() && 
           registrationDate.isValid();
}

QString Customer::getValidationError() const {
    if (id.isEmpty()) return "顾客ID不能为空";
    if (username.isEmpty()) return "用户名不能为空";
    if (passwordHash.isEmpty()) return "密码不能为空";
    if (!registrationDate.isValid()) return "注册时间无效";
    return "";
}

// ============================================================================
// AdminConfig 实现
// ============================================================================

AdminConfig::AdminConfig(const QString& passwordHash)
    : passwordHash(passwordHash)
    , lastModified(QDateTime::currentDateTime())
{
}

QJsonObject AdminConfig::toJson() const {
    QJsonObject json;
    json["passwordHash"] = passwordHash;
    json["lastModified"] = lastModified.toString(Qt::ISODate);
    return json;
}

AdminConfig AdminConfig::fromJson(const QJsonObject& json) {
    AdminConfig config;
    config.passwordHash = json["passwordHash"].toString();
    config.lastModified = QDateTime::fromString(json["lastModified"].toString(), Qt::ISODate);
    return config;
}

bool AdminConfig::isValid() const {
    return !passwordHash.isEmpty() && lastModified.isValid();
}

// ============================================================================
// MenuItem 实现
// ============================================================================

MenuItem::MenuItem(const QString& name, const QString& category, double price, 
                   int stock, const QString& description)
    : id(QUuid::createUuid().toString(QUuid::WithoutBraces))
    , name(name)
    , category(category)
    , price(price)
    , stock(stock)
    , description(description)
    , imageUrl("")
    , salesCount(0)
    , createdDate(QDateTime::currentDateTime())
    , lastModified(QDateTime::currentDateTime())
{
}

QJsonObject MenuItem::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["name"] = name;
    json["category"] = category;
    json["price"] = price;
    json["stock"] = stock;
    json["description"] = description;
    json["imageUrl"] = imageUrl;
    json["salesCount"] = salesCount;
    json["createdDate"] = createdDate.toString(Qt::ISODate);
    json["lastModified"] = lastModified.toString(Qt::ISODate);
    return json;
}

MenuItem MenuItem::fromJson(const QJsonObject& json) {
    MenuItem item;
    item.id = json["id"].toString();
    item.name = json["name"].toString();
    item.category = json["category"].toString();
    item.price = json["price"].toDouble();
    item.stock = json["stock"].toInt();
    item.description = json["description"].toString();
    item.imageUrl = json["imageUrl"].toString();
    item.salesCount = json["salesCount"].toInt();
    item.createdDate = QDateTime::fromString(json["createdDate"].toString(), Qt::ISODate);
    item.lastModified = QDateTime::fromString(json["lastModified"].toString(), Qt::ISODate);
    return item;
}

bool MenuItem::isValid() const {
    return !id.isEmpty() && !name.isEmpty() && !category.isEmpty() && 
           price >= 0 && stock >= 0 && createdDate.isValid();
}

QString MenuItem::getValidationError() const {
    if (id.isEmpty()) return "菜品ID不能为空";
    if (name.isEmpty()) return "菜品名称不能为空";
    if (category.isEmpty()) return "菜品分类不能为空";
    if (price < 0) return "价格不能为负数";
    if (stock < 0) return "库存不能为负数";
    if (!createdDate.isValid()) return "创建时间无效";
    return "";
}

bool MenuItem::updateStock(int newStock) {
    if (newStock < 0) return false;
    stock = newStock;
    lastModified = QDateTime::currentDateTime();
    return true;
}

// ============================================================================
// OrderStatus 辅助函数
// ============================================================================

QString orderStatusToString(OrderStatus status) {
    switch (status) {
        case OrderStatus::PENDING: return "待处理";
        case OrderStatus::PREPARING: return "制作中";
        case OrderStatus::COMPLETED: return "已完成";
        case OrderStatus::CANCELLED: return "已取消";
        default: return "未知状态";
    }
}

OrderStatus stringToOrderStatus(const QString& statusStr) {
    if (statusStr == "待处理") return OrderStatus::PENDING;
    if (statusStr == "制作中") return OrderStatus::PREPARING;
    if (statusStr == "已完成") return OrderStatus::COMPLETED;
    if (statusStr == "已取消") return OrderStatus::CANCELLED;
    return OrderStatus::PENDING; // 默认值
}

// ============================================================================
// OrderItem 实现
// ============================================================================

OrderItem::OrderItem(const QString& menuItemId, const QString& menuItemName, 
                     double price, int quantity)
    : menuItemId(menuItemId)
    , menuItemName(menuItemName)
    , price(price)
    , quantity(quantity)
    , subtotal(price * quantity)
{
}

QJsonObject OrderItem::toJson() const {
    QJsonObject json;
    json["menuItemId"] = menuItemId;
    json["menuItemName"] = menuItemName;
    json["price"] = price;
    json["quantity"] = quantity;
    json["subtotal"] = subtotal;
    return json;
}

OrderItem OrderItem::fromJson(const QJsonObject& json) {
    OrderItem item;
    item.menuItemId = json["menuItemId"].toString();
    item.menuItemName = json["menuItemName"].toString();
    item.price = json["price"].toDouble();
    item.quantity = json["quantity"].toInt();
    item.subtotal = json["subtotal"].toDouble();
    return item;
}

bool OrderItem::isValid() const {
    return !menuItemId.isEmpty() && !menuItemName.isEmpty() && 
           price >= 0 && quantity > 0 && subtotal >= 0;
}

// ============================================================================
// Order 实现
// ============================================================================

Order::Order(const QString& customerId, const QList<OrderItem>& items, 
             const QString& paymentMethod)
    : id(QUuid::createUuid().toString(QUuid::WithoutBraces))
    , customerId(customerId)
    , items(items)
    , totalAmount(0)
    , status(OrderStatus::PENDING)
    , createdDate(QDateTime::currentDateTime())
    , paymentMethod(paymentMethod)
{
    calculateTotal();
}

QJsonObject Order::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["customerId"] = customerId;
    
    QJsonArray itemsArray;
    for (const auto& item : items) {
        itemsArray.append(item.toJson());
    }
    json["items"] = itemsArray;
    
    json["totalAmount"] = totalAmount;
    json["status"] = static_cast<int>(status);
    json["statusText"] = orderStatusToString(status);
    json["createdDate"] = createdDate.toString(Qt::ISODate);
    
    if (completedDate.isValid()) {
        json["completedDate"] = completedDate.toString(Qt::ISODate);
    }
    
    json["paymentMethod"] = paymentMethod;
    return json;
}

Order Order::fromJson(const QJsonObject& json) {
    Order order;
    order.id = json["id"].toString();
    order.customerId = json["customerId"].toString();
    
    QJsonArray itemsArray = json["items"].toArray();
    for (const auto& value : itemsArray) {
        order.items.append(OrderItem::fromJson(value.toObject()));
    }
    
    order.totalAmount = json["totalAmount"].toDouble();
    order.status = static_cast<OrderStatus>(json["status"].toInt());
    order.createdDate = QDateTime::fromString(json["createdDate"].toString(), Qt::ISODate);
    
    if (json.contains("completedDate") && !json["completedDate"].toString().isEmpty()) {
        order.completedDate = QDateTime::fromString(json["completedDate"].toString(), Qt::ISODate);
    }
    
    order.paymentMethod = json["paymentMethod"].toString();
    return order;
}

bool Order::isValid() const {
    return !id.isEmpty() && !customerId.isEmpty() && !items.isEmpty() && 
           totalAmount >= 0 && createdDate.isValid();
}

QString Order::getValidationError() const {
    if (id.isEmpty()) return "订单ID不能为空";
    if (customerId.isEmpty()) return "顾客ID不能为空";
    if (items.isEmpty()) return "订单项不能为空";
    if (totalAmount < 0) return "订单总金额不能为负数";
    if (!createdDate.isValid()) return "订单创建时间无效";
    
    for (const auto& item : items) {
        if (!item.isValid()) {
            return QString("订单项无效: %1").arg(item.menuItemName);
        }
    }
    
    return "";
}

void Order::calculateTotal() {
    totalAmount = 0;
    for (auto& item : items) {
        item.calculateSubtotal();
        totalAmount += item.subtotal;
    }
}

bool Order::updateStatus(OrderStatus newStatus) {
    // 检查状态转换是否合法
    switch (status) {
        case OrderStatus::PENDING:
            if (newStatus != OrderStatus::PREPARING && newStatus != OrderStatus::CANCELLED) {
                return false;
            }
            break;
        case OrderStatus::PREPARING:
            if (newStatus != OrderStatus::COMPLETED && newStatus != OrderStatus::CANCELLED) {
                return false;
            }
            break;
        case OrderStatus::COMPLETED:
        case OrderStatus::CANCELLED:
            return false; // 已完成或已取消的订单不能再改变状态
    }
    
    status = newStatus;
    if (newStatus == OrderStatus::COMPLETED) {
        completedDate = QDateTime::currentDateTime();
    }
    
    return true;
}

int Order::getTotalItems() const {
    int total = 0;
    for (const auto& item : items) {
        total += item.quantity;
    }
    return total;
}

// ============================================================================
// Rating 实现
// ============================================================================

Rating::Rating(const QString& orderId, const QString& customerName, 
               int rating, const QString& comment)
    : id(QUuid::createUuid().toString(QUuid::WithoutBraces))
    , orderId(orderId)
    , customerName(customerName)
    , rating(rating)
    , comment(comment)
    , createdDate(QDateTime::currentDateTime())
{
}

QJsonObject Rating::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["orderId"] = orderId;
    json["customerName"] = customerName;
    json["rating"] = rating;
    json["comment"] = comment;
    json["createdDate"] = createdDate.toString(Qt::ISODate);
    return json;
}

Rating Rating::fromJson(const QJsonObject& json) {
    Rating rating;
    rating.id = json["id"].toString();
    rating.orderId = json["orderId"].toString();
    rating.customerName = json["customerName"].toString();
    rating.rating = json["rating"].toInt();
    rating.comment = json["comment"].toString();
    rating.createdDate = QDateTime::fromString(json["createdDate"].toString(), Qt::ISODate);
    return rating;
}

bool Rating::isValid() const {
    return !id.isEmpty() && !orderId.isEmpty() && !customerName.isEmpty() && 
           isValidRating() && createdDate.isValid();
}

QString Rating::getValidationError() const {
    if (id.isEmpty()) return "评分ID不能为空";
    if (orderId.isEmpty()) return "订单ID不能为空";
    if (customerName.isEmpty()) return "顾客用户名不能为空";
    if (!isValidRating()) return "评分必须在1-5星之间";
    if (!createdDate.isValid()) return "评分时间无效";
    if (comment.length() > 500) return "评价内容不能超过500字";
    return "";
}

// ============================================================================
// Statistics 实现
// ============================================================================

QJsonObject Statistics::toJson() const {
    QJsonObject json;
    
    // 库存信息
    QJsonArray stockArray;
    for (const auto& info : stockInfos) {
        QJsonObject stockJson;
        stockJson["menuItemId"] = info.menuItemId;
        stockJson["menuItemName"] = info.menuItemName;
        stockJson["currentStock"] = info.currentStock;
        stockJson["lowStockThreshold"] = info.lowStockThreshold;
        stockJson["isLowStock"] = info.isLowStock();
        stockArray.append(stockJson);
    }
    json["stockInfos"] = stockArray;
    
    // 销量信息
    QJsonArray salesArray;
    for (const auto& info : salesInfos) {
        QJsonObject salesJson;
        salesJson["menuItemId"] = info.menuItemId;
        salesJson["menuItemName"] = info.menuItemName;
        salesJson["totalSales"] = info.totalSales;
        salesJson["totalRevenue"] = info.totalRevenue;
        salesArray.append(salesJson);
    }
    json["salesInfos"] = salesArray;
    
    // 评分信息
    QJsonObject ratingJson;
    ratingJson["averageRating"] = overallRating.averageRating;
    ratingJson["totalRatings"] = overallRating.totalRatings;
    
    QJsonArray distributionArray;
    for (int count : overallRating.ratingDistribution) {
        distributionArray.append(count);
    }
    ratingJson["ratingDistribution"] = distributionArray;
    json["overallRating"] = ratingJson;
    
    return json;
}

Statistics Statistics::fromJson(const QJsonObject& json) {
    Statistics stats;
    
    // 库存信息
    QJsonArray stockArray = json["stockInfos"].toArray();
    for (const auto& value : stockArray) {
        QJsonObject stockJson = value.toObject();
        StockInfo info;
        info.menuItemId = stockJson["menuItemId"].toString();
        info.menuItemName = stockJson["menuItemName"].toString();
        info.currentStock = stockJson["currentStock"].toInt();
        info.lowStockThreshold = stockJson["lowStockThreshold"].toInt();
        stats.stockInfos.append(info);
    }
    
    // 销量信息
    QJsonArray salesArray = json["salesInfos"].toArray();
    for (const auto& value : salesArray) {
        QJsonObject salesJson = value.toObject();
        SalesInfo info;
        info.menuItemId = salesJson["menuItemId"].toString();
        info.menuItemName = salesJson["menuItemName"].toString();
        info.totalSales = salesJson["totalSales"].toInt();
        info.totalRevenue = salesJson["totalRevenue"].toDouble();
        stats.salesInfos.append(info);
    }
    
    // 评分信息
    QJsonObject ratingJson = json["overallRating"].toObject();
    stats.overallRating.averageRating = ratingJson["averageRating"].toDouble();
    stats.overallRating.totalRatings = ratingJson["totalRatings"].toInt();
    
    QJsonArray distributionArray = ratingJson["ratingDistribution"].toArray();
    stats.overallRating.ratingDistribution.clear();
    for (const auto& value : distributionArray) {
        stats.overallRating.ratingDistribution.append(value.toInt());
    }
    
    return stats;
}

// ============================================================================
// UserSettings 实现
// ============================================================================

QJsonObject UserSettings::toJson() const {
    QJsonObject json;
    json["userId"] = userId;
    json["theme"] = theme;
    json["fontSize"] = fontSize;
    json["enableNotifications"] = enableNotifications;
    json["autoLogin"] = autoLogin;
    json["language"] = language;
    json["lastModified"] = lastModified.toString(Qt::ISODate);
    return json;
}

UserSettings UserSettings::fromJson(const QJsonObject& json) {
    UserSettings settings;
    settings.userId = json["userId"].toString();
    settings.theme = json["theme"].toString("light");
    settings.fontSize = json["fontSize"].toInt(12);
    settings.enableNotifications = json["enableNotifications"].toBool(true);
    settings.autoLogin = json["autoLogin"].toBool(false);
    settings.language = json["language"].toString("zh_CN");
    settings.lastModified = QDateTime::fromString(json["lastModified"].toString(), Qt::ISODate);
    
    // 如果lastModified无效，设置为当前时间
    if (!settings.lastModified.isValid()) {
        settings.lastModified = QDateTime::currentDateTime();
    }
    
    return settings;
}

bool UserSettings::isValid() const {
    return !userId.isEmpty() && 
           isValidTheme(theme) && 
           isValidFontSize(fontSize) &&
           isValidLanguage(language) &&
           lastModified.isValid();
}

QString UserSettings::getValidationError() const {
    if (userId.isEmpty()) return "用户ID不能为空";
    if (!isValidTheme(theme)) return QString("无效的主题设置: %1").arg(theme);
    if (!isValidFontSize(fontSize)) return QString("无效的字体大小: %1").arg(fontSize);
    if (!isValidLanguage(language)) return QString("无效的语言设置: %1").arg(language);
    if (!lastModified.isValid()) return "最后修改时间无效";
    return QString();
}

bool UserSettings::isValidTheme(const QString& themeValue) const {
    static QStringList validThemes = {"light", "dark", "auto"};
    return validThemes.contains(themeValue);
}

bool UserSettings::isValidFontSize(int size) const {
    return size >= 9 && size <= 16;
}

bool UserSettings::isValidLanguage(const QString& lang) const {
    static QStringList validLanguages = {"zh_CN", "en_US"};
    return validLanguages.contains(lang);
}

// ============================================================================
// 重新下单功能相关实现
// ============================================================================

// 重新下单错误码辅助函数实现
QString reorderErrorCodeToString(ReorderErrorCode code) {
    switch (code) {
        case ReorderErrorCode::SUCCESS: return "成功";
        case ReorderErrorCode::USER_NOT_LOGIN: return "用户未登录";
        case ReorderErrorCode::ORDER_NOT_FOUND: return "订单不存在";
        case ReorderErrorCode::CART_FULL: return "购物车已满";
        case ReorderErrorCode::ALL_ITEMS_UNAVAILABLE: return "所有菜品都不可用";
        case ReorderErrorCode::SYSTEM_ERROR: return "系统错误";
        case ReorderErrorCode::DATA_ACCESS_ERROR: return "数据访问错误";
        case ReorderErrorCode::NETWORK_ERROR: return "网络错误";
        default: return "未知错误";
    }
}

ReorderErrorCode stringToReorderErrorCode(const QString& codeStr) {
    if (codeStr == "成功") return ReorderErrorCode::SUCCESS;
    if (codeStr == "用户未登录") return ReorderErrorCode::USER_NOT_LOGIN;
    if (codeStr == "订单不存在") return ReorderErrorCode::ORDER_NOT_FOUND;
    if (codeStr == "购物车已满") return ReorderErrorCode::CART_FULL;
    if (codeStr == "所有菜品都不可用") return ReorderErrorCode::ALL_ITEMS_UNAVAILABLE;
    if (codeStr == "系统错误") return ReorderErrorCode::SYSTEM_ERROR;
    if (codeStr == "数据访问错误") return ReorderErrorCode::DATA_ACCESS_ERROR;
    if (codeStr == "网络错误") return ReorderErrorCode::NETWORK_ERROR;
    return ReorderErrorCode::SYSTEM_ERROR; // 默认值
}

// ============================================================================
// ItemValidationResult 实现
// ============================================================================

QJsonObject ItemValidationResult::toJson() const {
    QJsonObject json;
    json["isAvailable"] = isAvailable;
    json["hasStock"] = hasStock;
    json["availableQuantity"] = availableQuantity;
    json["requestedQuantity"] = requestedQuantity;
    json["currentItem"] = currentItem.toJson();
    json["errorMessage"] = errorMessage;
    return json;
}

ItemValidationResult ItemValidationResult::fromJson(const QJsonObject& json) {
    ItemValidationResult result;
    result.isAvailable = json["isAvailable"].toBool();
    result.hasStock = json["hasStock"].toBool();
    result.availableQuantity = json["availableQuantity"].toInt();
    result.requestedQuantity = json["requestedQuantity"].toInt();
    result.currentItem = MenuItem::fromJson(json["currentItem"].toObject());
    result.errorMessage = json["errorMessage"].toString();
    return result;
}

// ============================================================================
// ReorderResult 实现
// ============================================================================

QJsonObject ReorderResult::toJson() const {
    QJsonObject json;
    json["isSuccess"] = isSuccess;
    json["errorCode"] = static_cast<int>(errorCode);
    json["errorCodeText"] = reorderErrorCodeToString(errorCode);
    json["totalItems"] = totalItems;
    json["successItems"] = successItems;
    json["partialItems"] = partialItems;
    json["failedItems"] = failedItems;
    
    QJsonArray unavailableArray;
    for (const QString& item : unavailableItems) {
        unavailableArray.append(item);
    }
    json["unavailableItems"] = unavailableArray;
    
    QJsonArray insufficientArray;
    for (const QString& item : insufficientItems) {
        insufficientArray.append(item);
    }
    json["insufficientItems"] = insufficientArray;
    
    QJsonArray successArray;
    for (const QString& item : successItemsDetails) {
        successArray.append(item);
    }
    json["successItemsDetails"] = successArray;
    
    QJsonArray validationArray;
    for (const ItemValidationResult& result : validationResults) {
        validationArray.append(result.toJson());
    }
    json["validationResults"] = validationArray;
    
    json["message"] = message;
    json["totalAmount"] = totalAmount;
    json["processTime"] = processTime.toString(Qt::ISODate);
    
    return json;
}

ReorderResult ReorderResult::fromJson(const QJsonObject& json) {
    ReorderResult result;
    result.isSuccess = json["isSuccess"].toBool();
    result.errorCode = static_cast<ReorderErrorCode>(json["errorCode"].toInt());
    result.totalItems = json["totalItems"].toInt();
    result.successItems = json["successItems"].toInt();
    result.partialItems = json["partialItems"].toInt();
    result.failedItems = json["failedItems"].toInt();
    
    QJsonArray unavailableArray = json["unavailableItems"].toArray();
    for (const auto& value : unavailableArray) {
        result.unavailableItems.append(value.toString());
    }
    
    QJsonArray insufficientArray = json["insufficientItems"].toArray();
    for (const auto& value : insufficientArray) {
        result.insufficientItems.append(value.toString());
    }
    
    QJsonArray successArray = json["successItemsDetails"].toArray();
    for (const auto& value : successArray) {
        result.successItemsDetails.append(value.toString());
    }
    
    QJsonArray validationArray = json["validationResults"].toArray();
    for (const auto& value : validationArray) {
        result.validationResults.append(ItemValidationResult::fromJson(value.toObject()));
    }
    
    result.message = json["message"].toString();
    result.totalAmount = json["totalAmount"].toDouble();
    result.processTime = QDateTime::fromString(json["processTime"].toString(), Qt::ISODate);
    
    return result;
}

bool ReorderResult::isValid() const {
    return totalItems >= 0 && successItems >= 0 && partialItems >= 0 && 
           failedItems >= 0 && (successItems + partialItems + failedItems) <= totalItems &&
           totalAmount >= 0 && processTime.isValid();
}

QString ReorderResult::getValidationError() const {
    if (totalItems < 0) return "总项目数不能为负数";
    if (successItems < 0) return "成功项目数不能为负数";
    if (partialItems < 0) return "部分成功项目数不能为负数";
    if (failedItems < 0) return "失败项目数不能为负数";
    if ((successItems + partialItems + failedItems) > totalItems) return "项目数统计不一致";
    if (totalAmount < 0) return "总金额不能为负数";
    if (!processTime.isValid()) return "处理时间无效";
    return "";
}

QString ReorderResult::generateUserMessage() const {
    if (isCompleteFailure()) {
        return QString("重新下单失败：%1").arg(reorderErrorCodeToString(errorCode));
    }
    
    if (isCompleteSuccess()) {
        return QString("重新下单成功！共添加 %1 个菜品，总金额 ¥%2")
               .arg(successItems)
               .arg(totalAmount, 0, 'f', 2);
    }
    
    if (isPartialSuccess()) {
        QString msg = QString("重新下单部分成功！");
        if (successItems > 0) {
            msg += QString("成功添加 %1 个菜品").arg(successItems);
        }
        if (partialItems > 0) {
            if (successItems > 0) msg += "，";
            msg += QString("%1 个菜品部分添加").arg(partialItems);
        }
        if (failedItems > 0) {
            msg += QString("，%1 个菜品无法添加").arg(failedItems);
        }
        msg += QString("。总金额 ¥%1").arg(totalAmount, 0, 'f', 2);
        
        if (!unavailableItems.isEmpty()) {
            msg += QString("。不可用菜品：%1").arg(unavailableItems.join("、"));
        }
        if (!insufficientItems.isEmpty()) {
            msg += QString("。库存不足菜品：%1").arg(insufficientItems.join("、"));
        }
        
        return msg;
    }
    
    return QString("重新下单完成，详情请查看购物车");
}

QString ReorderResult::generateDetailedReport() const {
    QString report;
    
    report += QString("=== 重新下单详细报告 ===\n");
    report += QString("处理时间：%1\n").arg(processTime.toString("yyyy-MM-dd hh:mm:ss"));
    report += QString("订单状态：%1\n").arg(reorderErrorCodeToString(errorCode));
    report += QString("总项目数：%1\n").arg(totalItems);
    report += QString("成功添加：%1 个\n").arg(successItems);
    report += QString("部分添加：%1 个\n").arg(partialItems);
    report += QString("添加失败：%1 个\n").arg(failedItems);
    report += QString("成功率：%1%\n").arg(getSuccessRate() * 100, 0, 'f', 1);
    report += QString("总金额：¥%1\n").arg(totalAmount, 0, 'f', 2);
    
    if (!successItemsDetails.isEmpty()) {
        report += QString("\n--- 成功添加的菜品 ---\n");
        for (const QString& item : successItemsDetails) {
            report += QString("✓ %1\n").arg(item);
        }
    }
    
    if (!unavailableItems.isEmpty()) {
        report += QString("\n--- 不可用菜品 ---\n");
        for (const QString& item : unavailableItems) {
            report += QString("✗ %1（菜品已下架）\n").arg(item);
        }
    }
    
    if (!insufficientItems.isEmpty()) {
        report += QString("\n--- 库存不足菜品 ---\n");
        for (const QString& item : insufficientItems) {
            report += QString("⚠ %1（库存不足）\n").arg(item);
        }
    }
    
    if (!message.isEmpty()) {
        report += QString("\n备注：%1\n").arg(message);
    }
    
    return report;
}

} // namespace RestaurantSystem
